import 'package:app_updater/app_updater.dart';
import 'package:app_updater/entity/download_record.dart';
import 'package:flutter/material.dart';

import 'apis.dart';
import 'model/app_upgrade.dart';
import 'widget/updater_dialog.dart';

class AppUpdaterPage extends StatefulWidget {
  const AppUpdaterPage({Key? key}) : super(key: key);

  @override
  State<AppUpdaterPage> createState() => _AppUpdaterPageState();
}

class _AppUpdaterPageState extends State<AppUpdaterPage> {
  final AppUpdater _plugin = AppUpdater();

  final ValueNotifier<AppUpgrade?> _upgradeNotifier =
      ValueNotifier<AppUpgrade?>(null);

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('App Updater'),
        elevation: 1,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: SizedBox(
          width: double.infinity,
          child: Column(
            children: <Widget>[
              ValueListenableBuilder<AppUpgrade?>(
                valueListenable: _upgradeNotifier,
                builder:
                    (BuildContext context, AppUpgrade? value, Widget? child) {
                  return Text(value?.toString() ?? '');
                },
              ),
              const SizedBox(height: 20),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: _onCheckForUpdatesPressed,
                child: const Text('检查更新'),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: _onClearRecordPressed,
                // color: theme.errorColor,
                child: const Text('清除记录'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _onCheckForUpdatesPressed() {
    return AppUpdaterApis.upgrade().then((AppUpgrade upgrade) {
      if (!mounted) {
        return;
      }

      _upgradeNotifier.value = upgrade;
      print(upgrade.toJson());
      showDialog(
        context: context,
        builder: (BuildContext context) {
          // return Container();
          return AppUpdaterDialog(upgrade: upgrade);
        },
      );
    });
  }

  Future<int> _onClearRecordPressed() {
    return _plugin.downloadRecord.then((DownloadRecord? record) {
      if (record == null) {
        return Future<int>.value(0);
      }
      return _plugin.removeDownload(<int>[record.downloadId]);
    }).then((int numOfRemoved) {
      return Future.wait(<Future<void>>[
        _plugin.deleteDownloadRecord(),
        _plugin.deleteInstallationRecord(),
      ]).then((void value) {
        if (numOfRemoved > 0) {
          // AppToast.showSuccess('移除$numOfRemoved项下载');
        }

        return numOfRemoved;
      });
    });
  }
}
